<?php
/**
 * 用户答复模型
 *
 *@author hary <hary@taomee.com>
 */
class response_model extends model
{
	private $response_table;

	function __construct()
	{
		parent::__construct();
		$this->loadModel("form_model");
		$this->response_table = "response";
	}

	/**
	 * 添加一个answer
	 * @param $response
	 * @return boolean
	 */
	public function addResponseItem($response){

		$response = $this->formatData($response);
			
		if(strlen($response['r_answer'])>$this->sys_conf_var['survey']['answer']['max'])
		{
			$response['r_answer'] = substr($response['r_answer'],0,$this->sys_conf_var['survey']['answer']['max']);
		}
			
		if(!is_array($response)) return false;
			
		$arr['r_entry_id'] 	  = $response['r_entry_id'];
		$arr['r_answer'] 	  = $response['r_answer'];
		$arr['r_submit_time'] = $response['r_submit_time'];
		$arr['r_submit_ip']   = $response['r_submit_ip'];
		$arr['r_form_key']    = $response['r_form_key'];
			
		$this->addData($arr);
			
		return $this->dataInsert($this->response_table);
	}

	/**
	 * 根据id删除表单
	 * @param $id
	 * @return boolean
	 */
	public function delResponseItemById($id){

		if(!is_numeric($id)) return false;
			
		$this->where('r_id',$id,'=','and',0);
			
		return $this->dataDel($this->response_table);
	}

	/**
	 * 根据id获取获取answer
	 * @param $id
	 * @return max
	 */
	public function getResponseItemById($id){

		if(!is_numeric($id)) return false;
			
		$this->where('r_id',$id,'=','and',0);
			
		return $this->getDataInfo($this->response_table);
			
	}

	/**
	 * 根据id获取获取answer
	 * @param $id
	 * @return max
	 */
	public function getResponseItemsByFormEntryId($key,$id){

		$key = $this->formatData($key);

		if(!is_numeric($id)) return false;
			
		$this->where('r_form_key',$key);
		$this->where('r_entry_id',$id,'=','and',0);
			
		return $this->getDataList($this->response_table);
			
	}

	/**
	 * 分析数据
	 * @return unknown_type
	 */
	public function analizyResponse($key){

		$form = $this->form_model->getFormItemByKey($key);

		$NumResponses = $this->getResponseNumByFormKey($key);

		if(empty($NumResponses))
		{
			return false;
		}

		if(empty($form['f_start_time'])) $form['f_start_time'] = time();

		$start_time = mktime(0,0,0,date("m",$form['f_start_time']),date("d",$form['f_start_time']),date("Y",$form['f_start_time']));
		$end_time	= mktime(0,0,0,date("m",time()),date("d",time()),date("Y",time()));

		$ResponseDates 	  = array(date("Y/m/d",$start_time),date("Y/m/d",$end_time));
		$ResponseCounters = array();
		$Entries          = array();

		//整体数据分析
		/*for($i=$start_time,$n=$i+3600*24;$start_time<=$i&&$i<=$end_time;$i=$i+3600*24,$n=$i+3600*24)
		{
			if($i==$end_time)
			{
				break;
			}

			$daily_num = $this->getResponseNumByCondition(" r_form_key='$key' and $i <= r_submit_time and r_submit_time <= $n group by r_submit_time ");
			
			if(!empty($daily_num)) $ResponseCounters[] = $daily_num;
		}*/

		$NumResponsesByDate = array('ResponseCounters'=>$ResponseCounters,'ResponseDates'=>$ResponseDates);

		//单项数据分析
		$entrys = $this->form_model->getEntryItemsByFormKey($key);

		foreach($entrys as $entry)
		{
			$EntryId = $entry['e_entry_id'];

			$responseEntries = $this->getResponseItemsByFormEntryId($key,$EntryId);

			$count   = count($responseEntries);
			$Label   = array();
			$Value   = array();
			$Percent = array();

			$Question = $entry['e_question_title'];

			switch ($entry['e_type'])
			{
				case 1:
				case 2:

					$num = $count<5?$count:5;

					for($rn=0;$rn<$num;$rn++)
					{
						$Value[] = $responseEntries[$rn]['r_answer'];
					}

					if($count>=5) $Value[] = "...";

					$Entry_ = array(
										"Text"=>$Value,
										"EntryId"=>$EntryId,
										"Question"=>$Question,
										"EntryType"=>$entry['e_type']
					);

					break;
				case 3:
				case 5:
					$objArr = json_decode($entry['e_choices']);
					$allValue=0;
					foreach($responseEntries as $res)
					{
						$res_key = $res['r_answer'];

						if(!is_numeric($res_key))
						{
							$index = count($objArr)-1;
							$Value[$index]++;
						}
						else
						{
							$Value[$res_key]++;
						}
					}

					for($n=0;$n<count($objArr);$n++)
					{
						$option    = $this->object2array($objArr[$n]);
						$Label[$n] = $option['Value'];

						if(empty($Value[$n]))
						{
							$Value[$n] = 0;
						}

					}

					for($e=0;$e<count($Value);$e++)
					{
						if(!empty($Value[$e])){
							$allValue+=intval($Value[$e]);
						}
					}



					ksort($Label);
					ksort($Value);
					ksort($Percent);

					$Entry_ = array(
										"Value"=>$Value,
										"Label"=>$Label,
										"EntryId"=>$EntryId,
										"Question"=>$Question,
										"allValue"=>$allValue,
										"EntryType"=>$entry['e_type']
					);

					break;
				case 4:
					$objArr = json_decode($entry['e_choices']);
					$allValue = 0;
						
					foreach($responseEntries as $res)
					{
						$values = json_decode($res['r_answer']);

						for($r=0;$r<count($values);$r++)
						{
							$res_key = $values[$r];

							if(!is_numeric($res_key))
							{
								$index = count($objArr)-1;
								$Value[$index]++;
							}
							else
							{
								$Value[$res_key]++;
							}
						}
					}

					for($n=0;$n<count($objArr);$n++)
					{
						$option    = $this->object2array($objArr[$n]);
						$Label[$n] = $option['Value'];

						if(empty($Value[$n]))
						{
							$Value[$n] = 0;
						}
					}

					for($e=0;$e<count($Label);$e++)
					{
						if(!empty($Value[$e]))
						{
							$allValue += intval($Value[$e]);
						}
					}
						
					ksort($Label);
					ksort($Value);
					ksort($Percent);

					$Entry_ = array(
										"Value"=>$Value,
										"Label"=>$Label,
										"EntryId"=>$EntryId,
										"Question"=>$Question,
										"allValue"=>$allValue,
										"EntryType"=>$entry['e_type']
					);

					break;
				default:
			}

			$Entries[] = $Entry_;

		}

		$analizyData = array('NumResponsesByDate'=>$NumResponsesByDate,
							 'NumResponses'=>$NumResponses,
							 'Entries'=>$Entries,
							 'Key'=>$key
		);

		return $analizyData;
	}

	/**
	 * 用户提交表单的时候进行分析统计
	 * @return array
	 */
	function resetAnalizyed($key,$formdata,$cachedata){
		
		$new_data = $this->dataCombin($key,$formdata,$cachedata);
		
		$general = $this->analizyGeneral($key);

		return array_merge($new_data,$general);

	}

	/**
	 * 清空数据
	 * @return boolean
	 */
	function clearData($key){

		$key = $this->formatData($key);

		$this->where('r_form_key',$key);

		return $this->dataDel($this->response_table);
	}

	/**
	 * 统计数据合并
	 * @return array
	 */
	function dataCombin($key,$formdata,$old_data){

		$Entries  = $old_data['Entries'];

		foreach($Entries as &$entry_)
		{
				
			$entry = $formdata[$entry_['EntryId']];
			
			switch($entry_['EntryType'])
			{
				case 1:
				case 2:
					if(count($entry_['Text'])<5)
					{
						$entry_['Text'][] = $entry['r_answer'];
					}
					break;
				case 3:
				case 5:
					$key = intval($entry['r_answer']);

					$entry_['Value'][$key]++;
					$entry_['allValue']++;
					break;
				case 4:

					$entry_ans = json_decode($entry['r_answer']);

					foreach($entry_ans as $key)
					{
						$entry_['Value'][$key]++;
						$entry_['allValue']++;
					}
					break;
				default:
					break;
			}
		}

		$old_data['Entries'] = $Entries;
		
		return $old_data;
	}


	/**
	 * 整体数据分析
	 * @return array
	 */
	function analizyGeneral($key){

		$form = $this->form_model->getFormItemByKey($key);

		$NumResponses = $this->getResponseNumByFormKey($key);

		if(empty($NumResponses))
		{
			return false;
		}

		if(empty($form['f_start_time'])) $form['f_start_time'] = time();

		$start_time = mktime(0,0,0,date("m",$form['f_start_time']),date("d",$form['f_start_time']),date("Y",$form['f_start_time']));
		$end_time	= mktime(0,0,0,date("m",time()),date("d",time()),date("Y",time()));

		$ResponseDates 	  = array(date("Y/m/d",$start_time),date("Y/m/d",$end_time));
		$ResponseCounters = array();
		$Entries          = array();

		//整体数据分析
		/*for($i=$start_time,$n=$i+3600*24;$start_time<=$i&&$i<=$end_time;$i=$i+3600*24,$n=$i+3600*24)
		{
			if($i==$end_time)
			{
				break;
			}

			$daily_num = $this->getResponseNumByCondition(" r_form_key='$key' and $i <= r_submit_time and r_submit_time <= $n group by r_submit_time ");
			
			if(!empty($daily_num)) $ResponseCounters[] = $daily_num;
		}*/

		$NumResponsesByDate = array('ResponseCounters'=>$ResponseCounters,'ResponseDates'=>$ResponseDates);

		return array('NumResponsesByDate'=>$NumResponsesByDate,'NumResponses'=>$NumResponses);
	}


	/**
	 * 更改answer
	 * @param $response
	 * @return max
	 */
	public function changeResponseItemById($response){
			
		$response = $this->formatData($response);
		$id  	  = $response['r_id'];
			
		if(!is_array($response)) return false;
			
		$arr['r_entry_id'] 	  = $response['r_entry_id'];
		$arr['r_answer'] 	  = $response['r_answer'];
		$arr['r_submit_time'] = $response['r_submit_time'];
		$arr['r_submit_ip']   = $response['r_submit_ip'];
		$arr['r_form_key']    = $response['r_form_key'];
			
		$this->addData($arr);
			
		$this->where('r_id',$id);
			
		return $this->dataUpdate($this->response_table);

	}

	/**
	 * 获取某个表单的回复数量
	 * @param $key
	 * @return unknown_type
	 */
	public function getResponseNumByFormKey($key){

		$key = $this->formatData($key);

		$sql = "select count(*) as num from (select r_submit_time from s_response where r_form_key ='$key' group by r_submit_time) as r ";

		$result =  $this->customQuery($sql,2);

		return $result['num'];
	}

	/**
	 * 根据条件获取某个表单的回复数量
	 * @param $key
	 * $type 如果等于1那么就返回数据，而不是num
	 * @return unknown_type
	 */
	public function getResponseNumByCondition($condition){

		$sql = "select count(*) as num from (select count(r_submit_time) from s_response where $condition) as r";

		$result =  $this->customQuery($sql,2);

		return $result['num'];
	}

	/**
	 * 根据条件获取多个answer
	 * @param $form_key
	 * @param $keywords
	 * @param $entry_id
	 * @param $submit_time
	 * @param $page
	 * @param $page_size
	 * @param $order
	 * @return max
	 */
	public function getResponseItems($form_key,$keywords="",$entry_id="",$submit_time="",$page='1',$page_size='10',$order='r_id desc'){

		$form_key 	 = $this->formatData($form_key);
		$keywords 	 = $this->formatData($keywords);
		$entry_id 	 = $this->formatData($entry_id);
		$submit_time = $this->formatData($submit_time);
			
		$sql = "select * from $this->response_table where ";

		if($form_key)    $sql .= " r_form_key = $form_key";
			
		if($entry_id)    $sql .= " and r_entry_id = $entry_id";
			
		if($submit_time) $sql .= " and r_submit_time = $submit_time";
			
		if($keywords)    $sql .= " and ( r_answer like '%$keywords%' or r_submit_ip like '%$keywords%' ) ";
			
		if($page) $this->setPage($page);
			
		if($page_size) $this->setLimit($page_size);
			
		if($order) $this->setOrder(' order by '.$order);
			
		return $this->customQuery($sql);
	}

}